package com.hqyj.project.realm;


import com.hqyj.project.entity.Role;
import com.hqyj.project.entity.User;
import com.hqyj.project.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义数据源
 */
@Slf4j
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取主要委托人
        String userName = (String) principalCollection.getPrimaryPrincipal();
        //查询用户的角色信息
        User user = userMapper.selectUserByUserName(userName);
        // 将权限信息封闭为AuthorizationInfo
        //获取用户角色
        List<Role> roleList = user.getRoleList();
        //创建空集合存储角色信息
        List<String> roleNames = new ArrayList<>();
        for (Role role : roleList) {
            roleNames.add(role.getRoleName());   //添加
        }
        //创建授权对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //将用户对应的角色信息（角色名）放入simpleAuthorizationInfo
        simpleAuthorizationInfo.addRoles(roleNames);

        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        String userName = (String) authenticationToken.getPrincipal();
        User user = userMapper.selectUserByUserName(userName);
        SecurityUtils.getSubject().getSession().setAttribute("u",user);
        if(user==null){
            return null;
        }
        ByteSource source = ByteSource.Util.bytes(user.getUserSalt());
        return new SimpleAuthenticationInfo(userName,user.getUserPwd(),source,getName());
    }
}
